package com.sanji.sjmallmodule.order;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.app.AlertDialog;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.ExpandableListView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.sanji.sjmallapp.MallApplication;
import com.sanji.sjmallapp.R;
import com.sanji.sjmallconfig.ConfigAPI;
import com.sanji.sjmallconfig.ConfigConts;
import com.sanji.sjmallmanager.http.NoHttpCallBack;
import com.sanji.sjmallmanager.http.NoHttpListener;
import com.sanji.sjmallutils.JsonParseUtil;
import com.sanji.sjmallutils.SharePreferenceUtil;
import com.sanji.sjmallutils.Tools;
import com.umeng.analytics.MobclickAgent;
import com.yolanda.nohttp.NoHttp;
import com.yolanda.nohttp.RequestMethod;
import com.yolanda.nohttp.rest.Request;
import com.yolanda.nohttp.rest.Response;

import org.json.JSONArray;
import org.json.JSONObject;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * 购物车
 */
public class ShopcarFragment extends Fragment implements ShopcarAdapter.MoneyChangeListener, View.OnClickListener, NoHttpListener {
    private static final int WHAT_CART_LIST = ConfigAPI.SHOP_CAR_LIST_URL.hashCode();
    private static final int WHAT_CART_DELT = ConfigAPI.SHOP_CAR_DELT_URL.hashCode();
    private static final int WHAT_CART_OPRT = ConfigAPI.SHOP_CAR_MODILY_URL.hashCode();
    @BindView(R.id.common_back_img)
    ImageView backImg;
    @BindView(R.id.common_title_tv)
    TextView titleTv;
    @BindView(R.id.common_right_tv)
    TextView operateTv;
    @BindView(R.id.shopcar_dest_view)
    ExpandableListView mListView;
    @BindView(R.id.shopcar_bom_all_layout)
    LinearLayout allBomLayout;//全选
    @BindView(R.id.shopcar_all_cb)
    CheckBox mAllCb;
    @BindView(R.id.shopcar_bom_layout)
    LinearLayout bomLayout;
    @BindView(R.id.shopcar_coust_tv)
    TextView coustTv;
    @BindView(R.id.shopcar_submi_btn)
    TextView submitTv;
    @BindView(R.id.list_view_null_linear)
    LinearLayout listViewNullLinear;
    @BindView(R.id.list_view_linear)
    LinearLayout listViewLinear;
    private Request<String> request;
    private ShopcarAdapter mShopcarAdapter;
    private List<ShopcarGroupBean> mGroupList = null;
    //是否编辑
    private boolean isOperate = false;
    //商品总额
    private double amount = 0.0;
    private View rootView;
    private SharePreferenceUtil myShare;
    private boolean isRefresh = true;

    private int modyGroup = 0;
    private int modyChild = 0;

    private AlertDialog.Builder deltDialog = null;

    public ShopcarFragment() {
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        if (rootView == null) {
            rootView = inflater.inflate(R.layout.fragment_shopcar, null);
            ButterKnife.bind(this, rootView);
            initView();
        }
        ButterKnife.bind(this, rootView);
        return rootView;
    }

    @Override
    public void onStart() {
        super.onStart();
        isRefresh = myShare.getBoolean(ConfigConts.IsRefresh, false);
        if (isRefresh) {
            mGroupList = new ArrayList<>();
            mAllCb.setChecked(false);
            //网络请求，请求完以后，置为false
            String url = ConfigAPI.SHOP_CAR_LIST_URL + myShare.getString(ConfigConts.USER_ID, "");
            request = NoHttp.createStringRequest(url, RequestMethod.GET);
            //设置取消标志
            request.setCancelSign(WHAT_CART_LIST);
            NoHttpCallBack.getInstance().add(getActivity(), WHAT_CART_LIST, request, this, true, true);
            myShare.put(ConfigConts.IsRefresh, false);
        }
    }

    private void initView() {
        backImg.setVisibility(View.GONE);
        titleTv.setVisibility(View.VISIBLE);
        titleTv.setText(getString(R.string.title_shopcar));
        operateTv.setVisibility(View.VISIBLE);
        operateTv.setText(getString(R.string.shopcar_edit));
        operateTv.setOnClickListener(this);
        submitTv.setOnClickListener(this);

        //去掉默认向下的箭头
        mListView.setGroupIndicator(null);

        mAllCb.setOnClickListener(this);
        myShare = MallApplication.myShare;
        myShare.put(ConfigConts.IsRefresh, true);
    }

    private void reSetMoney() {
        //计算总额
        amount = 0;
        int size = mGroupList.size();
        for (ShopcarGroupBean groupBean : mGroupList) {
            List<ShopcarChildBean> childBeenList = groupBean.getDestList();
            for (ShopcarChildBean childBean : childBeenList) {
                if (childBean.isSelected()) {
//                    double price = Tools.multiply(childBean.getGoodsPrice(), childBean.getGoodsCount());
                    double total = childBean.getSubTotal();
                    amount = Tools.add(amount, total);
                }
            }
        }
        coustTv.setText(getString(R.string.price_title) + amount);

        if (mGroupList.size() > 0) {
            allBomLayout.setVisibility(View.VISIBLE);
            operateTv.setVisibility(View.VISIBLE);
        } else {
            allBomLayout.setVisibility(View.GONE);
            operateTv.setVisibility(View.GONE);
        }
    }

    @Override
    public void onOptionsMenuClosed(Menu menu) {
        super.onOptionsMenuClosed(menu);
    }

    @Override
    public void onMoneyChange() {
        boolean allSelect = true;
        for (ShopcarGroupBean groupBean : mGroupList) {
            List<ShopcarChildBean> childList = groupBean.getDestList();
            for (ShopcarChildBean bean : childList) {
                if (!bean.isSelected()) {
                    allSelect = false;
                    break;
                }
            }
        }
        mAllCb.setChecked(allSelect);
        reSetMoney();
    }

    /**
     * adapter 中改变数量
     *
     * @param view
     * @param num
     */
    @Override
    public void onNumChange(final View view, final int group, final int child, final int num) {

        modyGroup = group;
        modyChild = child;

        ShopcarChildBean childBean = mGroupList.get(group).getDestList().get(child);

        try {
            JSONObject json = new JSONObject();
            json.put("id", childBean.getCartId());
            json.put("orderNum", num);

            Request<JSONObject> modyRequest = NoHttp.createJsonObjectRequest(ConfigAPI.SHOP_CAR_MODILY_URL, RequestMethod.POST);
            modyRequest.setDefineRequestBodyForJson(json);
            NoHttpCallBack.getInstance().add(getActivity(), ConfigAPI.SHOP_CAR_MODILY_URL.hashCode(), modyRequest, this, true, true);

        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    /**
     * 购物车删除的网络请求
     */

    private void shopcarDeltHttp() {
        try {
            Iterator<ShopcarGroupBean> groipIt = mGroupList.iterator();
            ShopcarGroupBean gbean = null;
            StringBuffer idsBuff = new StringBuffer();

            while (groipIt.hasNext()) {
                gbean = groipIt.next();
                Iterator<ShopcarChildBean> childIt = gbean.getDestList().iterator();
                ShopcarChildBean cbean = null;
                while (childIt.hasNext()) {
                    cbean = childIt.next();
                    if (cbean.isDelete()) {
                        idsBuff.append(cbean.getCartId()).append(",");
                    }
                }
            }

            if (idsBuff.length() > 0) {
                String deltIds = idsBuff.substring(0, idsBuff.length() - 1);

                Request<JSONObject> deltRequest = NoHttp.createJsonObjectRequest(ConfigAPI.SHOP_CAR_DELT_URL, RequestMethod.POST);
                JSONObject deltJson = new JSONObject();
                deltJson.put("cartIds", deltIds);
                deltRequest.setDefineRequestBodyForJson(deltJson);
                NoHttpCallBack.getInstance().add(getActivity(), ConfigAPI.SHOP_CAR_DELT_URL.hashCode(), deltRequest, this, true, true);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.shopcar_all_cb:
                boolean flag = mAllCb.isChecked();
                for (ShopcarGroupBean groupBean : mGroupList) {
                    groupBean.setAllSelected(flag);
                    List<ShopcarChildBean> childList = groupBean.getDestList();
                    for (ShopcarChildBean bean : childList) {
                        bean.setSelected(flag);
                    }
                }
                mAllCb.setChecked(flag);
                reSetMoney();
                mShopcarAdapter.notifyAdapter(mGroupList);
                break;
            case R.id.common_right_tv:
                //编辑
                if (!isOperate) {
                    isOperate = true;
                    operateTv.setText(getString(R.string.shopcar_delete));
                    operateTv.setTextColor(getResources().getColor(R.color.colorRed));
                    operateTv.setTextSize(18);
                    bomLayout.setVisibility(View.INVISIBLE);
                    submitTv.setVisibility(View.INVISIBLE);

                } else {
                    isOperate = false;
                    operateTv.setText(getString(R.string.shopcar_edit));
                    operateTv.setTextColor(getResources().getColor(R.color.color_686868));
                    operateTv.setTextSize(14);
                    bomLayout.setVisibility(View.VISIBLE);
                    submitTv.setVisibility(View.VISIBLE);

                    int size = 0;
                    for (ShopcarGroupBean groupBean : mGroupList) {
                        List<ShopcarChildBean> childList = groupBean.getDestList();
                        for (ShopcarChildBean bean : childList) {
                            if (bean.isSelected()) {
                                size++;
                            }
                        }
                    }
                    if (size > 0) {
                        //弹框确认
                        showDeltDialog();
                    }
                }
                break;
            case R.id.shopcar_submi_btn:
                if (isOperate) {
                    //删除
                    for (ShopcarGroupBean groupBean : mGroupList) {
                        if (groupBean.isAllSelected()) {
                            groupBean.setAllDelete(true);
                            List<ShopcarChildBean> childList = groupBean.getDestList();
                            for (ShopcarChildBean bean : childList) {
                                bean.setDelete(true);
                            }
                        } else {
                            List<ShopcarChildBean> childList = groupBean.getDestList();
                            for (ShopcarChildBean bean : childList) {
                                if (bean.isSelected()) {
                                    bean.setDelete(true);
                                }
                            }
                        }
                    }
                    mShopcarAdapter.notifyAdapter(mGroupList);
                } else {
                    //去结算
                    if (amount == 0) {
                        Toast.makeText(getActivity(), getString(R.string.shopcar_choose_goods), Toast.LENGTH_SHORT).show();
                        return;
                    }
                    Intent intent = new Intent(getActivity(), FirmOrderActivity.class);
                    List<ShopcarChildBean> childList = new ArrayList<>();
                    for (ShopcarGroupBean groupBean : mGroupList) {
                        if (groupBean.isAllSelected()) {
                            childList.addAll(groupBean.getDestList());
                        } else {
                            List<ShopcarChildBean> childs = groupBean.getDestList();
                            for (ShopcarChildBean child : childs) {
                                if (child.isSelected()) {
                                    childList.add(child);
                                }
                            }
                        }
                    }

                    Bundle bundle = new Bundle();
                    bundle.putSerializable("list", (Serializable) childList);
                    bundle.putDouble("amount", amount);
                    intent.putExtras(bundle);
                    startActivity(intent);
                }
                break;
        }
    }

    @Override
    public void onSuccessed(int what, Response response) {
        try {
            JSONObject respJson = new JSONObject(response.get().toString());
            String status = respJson.optString("status");
            if (ConfigConts.STATUS_SUCCESS.equals(status)) {
                //success
                if (what == WHAT_CART_LIST) {
                    //购物车列表
                    JSONObject result = respJson.optJSONObject("result");
                    JSONArray items = result.optJSONArray("cartItemList");
                    int length = items.length();
                    JSONObject goods;
                    if (length > 0) {
                        listViewNullLinear.setVisibility(View.GONE);
                        listViewLinear.setVisibility(View.VISIBLE);
                        for (int i = 0; i < length; i++) {
                            goods = items.optJSONObject(i);
                            String type = goods.optString("type");
                            //判断是否存在group
                            boolean isExist = false;
                            for (ShopcarGroupBean groupBean : mGroupList) {
                                if (type.equals(groupBean.getGoodsSpec())) {
                                    //已存在相同类型
                                    ShopcarChildBean childBean = JsonParseUtil.shopcarDetailParse(goods);
                                    groupBean.getDestList().add(childBean);
                                    isExist = true;
                                    break;
                                }
                            }
                            if (!isExist) {
                                //新建一个group
                                ShopcarGroupBean groupBean = new ShopcarGroupBean();
                                groupBean.setGoodsSpec(type);
                                List<ShopcarChildBean> mDestList = new ArrayList<>();
                                ShopcarChildBean childBean = JsonParseUtil.shopcarDetailParse(goods);
                                mDestList.add(childBean);
                                groupBean.setDestList(mDestList);
                                mGroupList.add(groupBean);
                            }
                        }
                        mShopcarAdapter = new ShopcarAdapter(this.getActivity(), mGroupList);
                        mListView.setAdapter(mShopcarAdapter);
                        mShopcarAdapter.setOnMoneyChangeListener(this);

                        for (int i = 0; i < mGroupList.size(); i++) {
                            mListView.expandGroup(i);
                        }
                        //全选操作
                        for (ShopcarGroupBean groupBean : mGroupList){
                            groupBean.setAllSelected(true);
                            List<ShopcarChildBean> childList = groupBean.getDestList();
                            for (ShopcarChildBean childBean : childList){
                                childBean.setSelected(true);
                            }
                        }
                        mAllCb.setChecked(true);
                    } else {
                        listViewNullLinear.setVisibility(View.VISIBLE);
                        listViewLinear.setVisibility(View.GONE);
                    }
                } else if (what == WHAT_CART_DELT) {
                    Tools.toastTools(getActivity(), getString(R.string.shopcar_delete_success));
                    Iterator<ShopcarGroupBean> groipIt = mGroupList.iterator();
                    ShopcarGroupBean gbean = null;
                    while (groipIt.hasNext()) {
                        gbean = groipIt.next();
                        if (gbean.isAllDelete()) {
                            groipIt.remove();
                            //增加图片显示效果
                            listViewNullLinear.setVisibility(View.VISIBLE);
                            listViewLinear.setVisibility(View.GONE);
                        } else {
                            listViewNullLinear.setVisibility(View.GONE);
                            listViewLinear.setVisibility(View.VISIBLE);
                            Iterator<ShopcarChildBean> childIt = gbean.getDestList().iterator();
                            ShopcarChildBean cbean = null;
                            while (childIt.hasNext()) {
                                cbean = childIt.next();
                                if (cbean.isDelete()) {
                                    childIt.remove();
                                }
                            }
                        }
                    }

                    mShopcarAdapter.notifyAdapter(mGroupList);
                } else if (what == WHAT_CART_OPRT) {
                    //修改购物车项
                    JSONObject result = respJson.optJSONObject("result");

                    double singlePrice = result.optDouble("singlePrice");
                    int count = result.optInt("quantity");
                    int stock = result.optInt("stock");
                    double total = result.optDouble("subTotalPrice");


                    ShopcarChildBean childBean = mGroupList.get(modyGroup).getDestList().get(modyChild);
                    childBean.setGoodsPrice(singlePrice);
                    childBean.setGoodsCount(count);
                    childBean.setSubTotal(total);
                    childBean.setInventoryCount(stock);
                    childBean.setLimitCount(stock);


                    mShopcarAdapter.notifyAdapter(mGroupList);
                }
            } else {
                String errorCode = respJson.optString("errorCode");
                if ("unshelfed".equals(errorCode)) {
                    //下架商品 删除
                    List<ShopcarChildBean> childs = mGroupList.get(modyGroup).getDestList();
                    if (childs.size() > 1) {
                        childs.remove(modyChild);
                    } else {
                        mGroupList.remove(modyGroup);
                    }
                }
                String error = respJson.optString("errorMsg");
                Tools.toastTools(getActivity(), error);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        reSetMoney();
    }

    @Override
    public void onFailed(int what, Response response) {
        Tools.toastTools(getActivity(), getString(R.string.request_false));
    }


    /**
     * 删除提醒
     */
    private void showDeltDialog() {
        if (deltDialog == null) {
            deltDialog = new AlertDialog.Builder(getActivity());
            deltDialog.setMessage(getString(R.string.shopcar_delete_choose_goods)).setPositiveButton(getString(R.string.title_sure), new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int i) {

                    //添加删除标记
                    for (ShopcarGroupBean groupBean : mGroupList) {
                        if (groupBean.isAllSelected()) {
                            groupBean.setAllDelete(true);
                            List<ShopcarChildBean> childList = groupBean.getDestList();
                            for (ShopcarChildBean bean : childList) {
                                bean.setDelete(true);
                            }
                        } else {
                            List<ShopcarChildBean> childList = groupBean.getDestList();
                            for (ShopcarChildBean bean : childList) {
                                if (bean.isSelected()) {
                                    bean.setDelete(true);
                                }
                            }
                        }
                    }

                    //将标记删除的数据删除
                    shopcarDeltHttp();
                }
            }).setNegativeButton(getString(R.string.title_cancel), new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int i) {
                    //取消删除标记
                    for (ShopcarGroupBean groupBean : mGroupList) {
                        groupBean.setAllSelected(false);
                        groupBean.setAllDelete(false);
                        List<ShopcarChildBean> childList = groupBean.getDestList();
                        for (ShopcarChildBean bean : childList) {
                            bean.setDelete(false);
                            bean.setSelected(false);
                        }
                    }
                    mShopcarAdapter.notifyAdapter(mGroupList);
                    mAllCb.setChecked(false);
                    coustTv.setText(getString(R.string.price_title) + 0.0);
                }
            }).create();
        }
        deltDialog.show();
    }

    @Override
    public void onResume() {
        super.onResume();
        MobclickAgent.onPageStart("ShopcarFragment");
    }

    @Override
    public void onPause() {
        super.onPause();
        MobclickAgent.onPageEnd("ShopcarFragment");
    }
}
